require "#{RAILS_ROOT}/lib/agent_tcp.rb"

class Computer < ActiveRecord::Base
  belongs_to :room
  has_many :incidents, :order => 'created_at DESC'
  validates_uniqueness_of :ip
  validates_uniqueness_of :name

  # Regex become on Ruby Doc :
  # http://www.ruby-doc.org/core/classes/Resolv/IPv4.html
  validates_format_of :ip, :with => /\A(\d+)\.(\d+)\.(\d+)\.(\d+)\z/, :message => "Cette IP n'est pas une Ipv4"

  PORT = 1234
  MOUNTPOINTS = %w(/ /tmp /var /virtual)

  def ping
    AgentTcp.new(ip,PORT).ping
  rescue Timeout::Error
      Incident.timeout(id);
      message = "Timeout"
  rescue Errno::ENETUNREACH
      message = "non accessible"
  rescue Errno::ECONNREFUSED
      message = "pas de port ouvert"
  end
  
  def ram
    AgentTcp.new(ip,PORT).ram
  rescue Timeout::Error
      Incident.timeout(id);
      message = "Timeout"
  rescue Errno::ENETUNREACH
      message = "non accessible"
  rescue Errno::ECONNREFUSED
      message = "pas de port ouvert"
  end

  def mpuse (mountpoint)
    AgentTcp.new(ip,PORT).mpuse(mountpoint)
  rescue Timeout::Error
      Incident.timeout(id);
      message = "Timeout"
  rescue Errno::ENETUNREACH
      message = "non accessible"
  rescue Errno::ECONNREFUSED
      message = "pas de port ouvert"
  end

  def ping_error?
    not Incident.count(:conditions => ["resolved_at IS NULL AND computer_id = ? AND kind = 'DOWN'", id]).zero?
  end

  def hdd_error?
    not Incident.count(:conditions => ["resolved_at IS NULL AND computer_id = ? AND kind = 'LOWMP'", id]).zero?
  end
  
  def ram_error?
    not Incident.count(:conditions => ["resolved_at IS NULL AND computer_id = ? AND kind = 'LOWRAM'", id]).zero?
  end
  
  def incidents_not_resolved?
    not incidents_not_resolved.empty?
  end
  
  def incidents_resolved?
    not incidents_resolved.empty?
  end
  
  def incidents_not_resolved
    Incident.find_all ["resolved_at IS NULL AND computer_id = ?", id]
  end
  
  def incident_resolved
    Incident.find_all ["resolved_at IS NOT NULL AND computer_id = ?", id]
  end
  
end
